import GlobDef from "./GlobDef";
import * as fs from "fs";

export default class LogFile{
    public static pLog: LogFile = null;
    public static getInstance(): LogFile {
        if (LogFile.pLog == null) {
            LogFile.pLog = new LogFile();
        }
        return LogFile.pLog;
    }

    //检测是否隔天
    public m_nInRunDay:number  = -1;
    private m_pRunFileID:number  = -1;

    private m_pRunFileError:number  = -1;
    public CheckFileReset(){
        var date = GlobDef.GetDate();
        var nRDay  = date.getDate();
        
        if(nRDay != this.m_nInRunDay){//重新打开文件
            this.m_nInRunDay  = nRDay;
            var strFile = "Log_"+date.getFullYear()+"_"+date.getMonth()+"_"+date.getDate();
            fs.open("./Log/"+strFile+".txt",'a','0666',function(err,fd){
                if(err){
                    console.log("打开文件失败");
                    LogFile.getInstance().m_nInRunDay    = -1;
                 }else{
                    LogFile.getInstance().m_pRunFileID = fd;
                }
            }.bind(this));

            var strError = "Error_"+date.getFullYear()+"_"+date.getMonth()+"_"+date.getDate();
            fs.open("./Log/"+strError+".txt",'a','0666',function(err,fd){
                if(err){
                    console.log("打开文件失败");
                    LogFile.getInstance().m_nInRunDay    = -1;
                 }else{
                    LogFile.getInstance().m_pRunFileError = fd;
                }
            }.bind(this));
        }
    }
    public OutError(str:string){
        if(this.m_pRunFileError != -1){
            
            var bufView = Buffer.from(GlobDef.dateFormat()+": "+str+"\n");
            
            fs.write(this.m_pRunFileError,bufView,0,bufView.length,null,function(err,written,buffer){
                if(err){
                   console.log("指定位置写入文件失败");
                }else{
                   //console.log(written);
                   //console.log(buffer.toString());
                }
            })
            // fs.fsync(fd,null);
            // fs.close(fd);   
        }
    }
    public OutLog(str:string){
        if(this.m_pRunFileID != -1){
            
            var bufView = Buffer.from(GlobDef.dateFormat()+": "+str+"\n");
            
            fs.write(this.m_pRunFileID,bufView,0,bufView.length,null,function(err,written,buffer){
                if(err){
                   console.log("指定位置写入文件失败");
                }else{
                   //console.log(written);
                   //console.log(buffer.toString());
                }
            })
            // fs.fsync(fd,null);
            // fs.close(fd);   
        }
    }

}